package com.base.monitor.module.biz.service.collect.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.base.monitor.framework.result.PageResult;
import com.base.monitor.framework.util.DiskUtils;
import com.base.monitor.module.biz.service.collect.CollectService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.util.*;

@Service
public class CollectServiceImpl implements CollectService {

    @Value("${collect.file.name}")
    private String fileName;

    @Value("${collect.size}")
    private Integer size;

    /**
     * 获取最新的50条采集数据
     */
    @Override
    public PageResult<Map<String, Object>> page() {
        // 最后一行是回车换行，所以这里取51行
        String collectListStr = DiskUtils.readLastRows(fileName, StandardCharsets.UTF_8, size + 1);
        if (StrUtil.isBlank(collectListStr)) {
            return new PageResult<>(0, new ArrayList<>());
        }
        List<String> split = new ArrayList<>(Arrays.asList(collectListStr.split("\r\n")));
        if (CollectionUtil.isEmpty(split)) {
            return new PageResult<>(0, new ArrayList<>());
        }

        List<Map<String, Object>> list = new ArrayList<>();
        for (String str : split) {
            Map<String, Object> collectData = JSONObject.parseObject(str, Map.class);
            list.add(collectData);
        }

        return new PageResult<>(split.size(), CollectionUtil.reverse(list));
    }
}
